package com.liangtian.mdm.dm.jsp.common;

import com.liangtian.mdm.base.utils.PlatForm;
import com.liangtian.mdm.dm.common.constant.TableConst;
import com.liangtian.mdm.dm.common.constant.UrlConst;
import com.liangtian.mdm.dm.common.enums.Type;
import org.apache.commons.lang3.StringUtils;
import com.liangtian.mdm.dm.config.model.AttrConfig;
import com.liangtian.mdm.dm.model.model.Model;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JspUtil {

    /**
     * 根据模型类型返回需要生成的页面
     * classType 数据类型【0-列表、1-父子树、2-分类树】
     *
     * @param modelType 模型类型 【0-主数据、1-字典表】
     */
    public static List<String> getPagesByModelType(String modelType) {
//		List<String> jspLst=new ArrayList<String>();
//		if("0".equals(modelType)){  //主数据类型
//			jspLst.add("main"); //如果是树模板，则调用
//			jspLst.add("2");  //需要生成申请页面
//			jspLst.add("add");   //新增页面
//			jspLst.add("edit");   //编辑页面
//			jspLst.add("approve");     //审核页面
//			jspLst.add("update");   //变更页面
//			jspLst.add("1");   //查询页面
//			jspLst.add("detail");   //详细页面
//			jspLst.add("updateHis");   //变更历史查询
//			jspLst.add("updateEdit");   //变更编辑页面
//			jspLst.add("batchImport");   //批量导入excel
//		}else if("1".equals(modelType)){  //字典类型
//			jspLst.add("main"); //如果是树模板，则调用
//			jspLst.add("2");  //需要生成申请页面
//			jspLst.add("add");   //新增页面
//			jspLst.add("edit");   //编辑页面
//			jspLst.add("wh");   //维护页面
//			jspLst.add("1");   //查询页面
//			jspLst.add("batchImport");   //批量导入excel
//		}
//		return jspLst;

        if ("0".equals(modelType)) {  //主数据类型
            return Type.mdmTypeList;
        } else if ("1".equals(modelType)) {  //字典类型
            return Type.dicTypeList;
        }
        return null;
    }

    public static String spellColumn(Model model, Type type) {

        String ret = "";
        //判断本模型是父子树还是分类树
        if ("1".equals(model.getClassType())) {//如果是父子树
            switch (type) {
                case ADD:
                    return "AddPid";
                case APPLY:
                    return "ApplyPid";
                case EDIT:
                    return "EditPid";
                case UPDATE:
                    return "UpdatePid";
                case UPDATEEDIT:
                    return "UpdateEditPid";
                case APPROVE:
                    return "ShPid";
                case DETAIL:
                    return "DetailPid";
                case MAIN:
                    return "MainPid";
                case QUERY:
                    return "ListPid";
                case UPDATEHIS:
                    return "UpdateHisPid";
                default:
                    return "pid";
            }
        } else if ("2".equals(model.getClassType())) {//如果是分类树
            switch (type) {
                case ADD:
                    return "AddColumn";
                case APPLY:
                    return "ApplyColumn";
                case EDIT:
                    return "EditColumn";
                case UPDATE:
                    return "UpdateColumn";
                case UPDATEEDIT:
                    return "UpdateEditColumn";
                case APPROVE:
                    return "ShColumn";
                case DETAIL:
                    return "DetailColumn";
                case MAIN:
                    return "MainColumn";
                case QUERY:
                    return "ListColumn";
                case UPDATEHIS:
                    return "UpdateHisColumn";
                default:
                    if (model.getClassColumn() != null) {
                        return model.getClassColumn().toLowerCase();
                    }
                    break;
            }
        }
        return ret;
    }


    public static String spellReJsp(Model model, String type) {
        String ret = "";

        switch (type) {
            case "0":
                return "jsp";
            case "1":
                return "js";
        }
        return ret;
    }

    public static String spellReType(Model model, String type) {
        String ret = "";
        String classType = model.getClassType();//是列表-0 父子树-1 分类树-2
        String modelType = model.getModelType();//是主数据-0   还是字典表-1
        if ("0".equals(classType)) {//如果是列表
            if ("0".equals(modelType)) {//如果是主数据
                switch (type) {
                    case "add":
                        return "add";
                    case "2":
                        return "apply";
                    case "applyDetail":
                        return "applyDetail";
                    case "edit":
                        return "edit";
                    case "wh":
                        return "wh";
                    case "update":
                        return "update";
                    case "updateAdd":
                        return "updateAdd";
                    case "updateEdit":
                        return "updateEdit";
                    case "approve":
                        return "approve";
                    case "detail":
                        return "detail";
                    case "1":
                        return "list";
                    case "updateHis":
                        return "updateHis";
                    case "batchImport":
                        return "batchImport";
                    case "checkFiles":
                        return "checkFiles";

                    default:
                        break;
                }
            } else if ("1".equals(modelType)) {//如果是字典
                switch (type) {
                    case "add":
                        return "add";
                    case "2":
                        return "apply";
                    case "applyDetail":
                        return "applyDetail";
                    case "edit":
                        return "edit";
                    case "wh":
                        return "wh";
                    case "update":
                        return "update";
                    case "updateAdd":
                        return "updateAdd";
                    case "updateEdit":
                        return "updateEdit";
                    case "approve":
                        return "approve";
                    case "detail":
                        return "detail";
                    case "1":
                        return "zdList";
                    case "updateHis":
                        return "updateHis";
                    case "batchImport":
                        return "batchImport";
                    case "checkFiles":
                        return "checkFiles";

                    default:
                        break;
                }
            }
        } else {
            if ("0".equals(modelType)) {//如果是主数据
                switch (type) {
                    case "add":
                        return "treeTabAdd";
                    case "2":
                        return "treeTabApply";
                    case "applyDetail":
                        return "treeTabApplyDetail";
                    case "edit":
                        return "treeTabEdit";
                    case "wh":
                        return "treeTabWh";
                    case "update":
                        return "treeTabUpdate";
                    case "updateEdit":
                        return "treeTabUpdateEdit";
                    case "approve":
                        return "treeTabApprove";
                    case "detail":
                        return "treeTabDetail";
                    case "1":
                        return "treeTabList";
                    case "updateHis":
                        return "treeTabUpdateHis";
                    case "batchImport":
                        return "treeBatchImport";
                    case "checkFiles":
                        return "treeTabCheckFiles";
                    case "main":
                        return "treeTabMain";
                    default:
                        break;
                }
            } else if ("1".equals(modelType)) {//如果是字典
                switch (type) {
                    case "add":
                        return "treeTabAdd";
                    case "2":
                        return "treeTabApply";
                    case "applyDetail":
                        return "treeTabApplyDetail";
                    case "edit":
                        return "treeTabEdit";
                    case "wh":
                        return "treeTabWh";
                    case "update":
                        return "treeTabUpdate";
                    case "updateEdit":
                        return "treeTabUpdateEdit";
                    case "approve":
                        return "treeTabApprove";
                    case "detail":
                        return "treeTabDetail";
                    case "1":
                        return "treeTabZdList";
                    case "updateHis":
                        return "treeTabUpdateHis";
                    case "batchImport":
                        return "treeBatchImport";
                    case "checkFiles":
                        return "treeTabCheckFiles";
                    case "main":
                        return "treeTabMain";

                    default:
                        break;
                }
            }
        }
        return ret;
    }

    //复制二次开发模板js
//	public static void copySecondaryTempFile(Model model){
//		String sourceFileUrlJs=PlatForm.getAbsolutePath()+UrlConst.TEMPLESECONDARYURL+"js/";  //jsp模板存放的路径
//		PlatForm.copySecondaryFile(sourceFileUrlJs, model.getTableName(), "0","0","JS"); //复制js模板
//	}

    /**
     * <p>TODO 普通列表模板（第一版，列表模板）</p>
     * <p>@param model </p>
     *
     * @author : xiaoliu
     * @date :2017年7月4日下午1:31:53
     */
    public static void copyTempFile(Model model) {
        String sourceFileUrlJsp = PlatForm.getAbsolutePath() + UrlConst.TEMPLEURL;  //jsp模板存放的路径
        String sourceFileUrlJs = PlatForm.getAbsolutePath() + UrlConst.TEMPLEURL + "js/";  //jsp模板存放的路径
        PlatForm.copyFile(sourceFileUrlJsp, model.getTableName(), model.getModelType(), model.getClassType(), "JSP"); //复制jsp模板
        PlatForm.copyFile(sourceFileUrlJs, model.getTableName(), model.getModelType(), model.getClassType(), "JS"); //复制js模板
    }

    /**
     * <p>TODO 多视图列表模板（第一版，刘晶添加，在原有普通列表模板的基础上，
     * 添加--以前模型设置的时候，并未将列表考虑多视图功能，
     * 万达项目万部单位用到了，所以，添加此功能）</p>
     * <p>@param model </p>
     *
     * @author : xiaoliu
     * @date :2017年7月4日下午1:31:53
     */

    public static void copyTempViewFile(Model model) {
        String sourceFileUrlJsp = PlatForm.getAbsolutePath() + UrlConst.TEMPLEViewURL;  //jsp模板存放的路径
        String sourceFileUrlJs = PlatForm.getAbsolutePath() + UrlConst.TEMPLEViewURL + "js/";  //jsp模板存放的路径
        PlatForm.copyFile(sourceFileUrlJsp, model.getTableName(), model.getModelType(), model.getClassType(), "JSP"); //复制jsp模板
        PlatForm.copyFile(sourceFileUrlJs, model.getTableName(), model.getModelType(), model.getClassType(), "JS"); //复制js模板
    }

    public static void copyTempDisFile(Model model) {
        String sourceFileUrlJsp = PlatForm.getAbsolutePath() + UrlConst.TEMPLEURL + "temple_disList.jsp";  //jsp文件存放位置
        String sourceFileUrlJs = PlatForm.getAbsolutePath() + UrlConst.TEMPLEURL + "js/temple_disList.js";  //js模板存放路径
        String newFileUrl = "";
        String prjectUrl = PlatForm.getAbsolutePath();   //项目webroot所在地址
        PlatForm.copyFile(new File(sourceFileUrlJsp), new File(prjectUrl + "am/" + model.getTableName() + "/" + model.getTableName() + "_" + "temple_disList.jsp".split("_")[1]));//复制jsp模板
        PlatForm.copyFile(new File(sourceFileUrlJs), new File(prjectUrl + "am/" + model.getTableName() + "/js/" + model.getTableName() + "_" + "temple_disList.js".split("_")[1])); //复制js模板

    }

    /**
     * <p>TODO 普通树模板（第二版，父子树，分类树）</p>
     * <p>@param model </p>
     *
     * @author : xiaoliu
     * @date :2017年7月4日下午2:31:53
     */
    public static void copyTreeTabFile(Model model) {
        String sourceFileUrlJsp = PlatForm.getAbsolutePath() + UrlConst.TREETABURL;  //jsp模板存放的路径
        String sourceFileUrlJs = PlatForm.getAbsolutePath() + UrlConst.TREETABURL + "js/";  //jsp模板存放的路径
        PlatForm.copyFile(sourceFileUrlJsp, model.getTableName(), model.getModelType(), model.getClassType(), "JSP"); //复制jsp模板
        PlatForm.copyFile(sourceFileUrlJs, model.getTableName(), model.getModelType(), model.getClassType(), "JS"); //复制js模板
    }

    /**
     * <p>TODO 多视图树模板（第三版，刘晶添加，在原有普通树模板的基础上，
     * 添加--以前模型设置的时候，并未将树考虑多视图功能，
     * 万达项目，中外运项目 内部单位，外部单位 用到了，所以，添加此功能）</p>
     * <p>@param model </p>
     *
     * @author : xiaoliu
     * @date :2017年7月4日下午2:33:43
     */
    public static void copyTreeTabViewFile(Model model) {
        String sourceFileUrlJsp = PlatForm.getAbsolutePath() + UrlConst.TREETABVIEWURL;  //jsp模板存放的路径
        String sourceFileUrlJs = PlatForm.getAbsolutePath() + UrlConst.TREETABVIEWURL + "js/";  //jsp模板存放的路径
        PlatForm.copyFile(sourceFileUrlJsp, model.getTableName(), model.getModelType(), model.getClassType(), "JSP"); //复制jsp模板
        PlatForm.copyFile(sourceFileUrlJs, model.getTableName(), model.getModelType(), model.getClassType(), "JS"); //复制js模板
    }

    /**
     * 复制模板到指定文件路径下弹出框类型jsp  js
     */
    public static void copyPopTempFile(Model model, String coluName) {
        String sourceFileUrlJsp = "";
        String sourceFileUrlJs = "";
        if ("".equals(coluName)) {
            sourceFileUrlJsp = PlatForm.getAbsolutePath() + UrlConst.BGPOPTEMPLEURL;  //jsp模板存放的路径
            sourceFileUrlJs = PlatForm.getAbsolutePath() + UrlConst.BGPOPTEMPLEURL + "js/";
        } else {
            sourceFileUrlJsp = PlatForm.getAbsolutePath() + UrlConst.POPTEMPLEURL;   //jsp模板存放的路径
            sourceFileUrlJs = PlatForm.getAbsolutePath() + UrlConst.POPTEMPLEURL + "js/";
        }
        PlatForm.copyPopFile(sourceFileUrlJsp, model.getTableName(), coluName, "JSP"); //复制jsp模板
        PlatForm.copyPopFile(sourceFileUrlJs, model.getTableName(), coluName, "JS"); //复制js模板
    }

    /**
     * 复制模板到指定文件路径下主从表，主表新增模板jsp  js
     */
    public static void copySubAddTempFile(Model model, String coluName) {
        String sourceFileUrlJsp = "";
        String sourceFileUrlJs = "";
        if ("".equals(coluName)) {
            sourceFileUrlJsp = PlatForm.getAbsolutePath() + UrlConst.SUBADDTEMPLEURL;  //jsp模板存放的路径
            sourceFileUrlJs = PlatForm.getAbsolutePath() + UrlConst.SUBADDTEMPLEURL + "js/";
        } else {
            sourceFileUrlJsp = PlatForm.getAbsolutePath() + UrlConst.POPTEMPLEURL;   //jsp模板存放的路径
            sourceFileUrlJs = PlatForm.getAbsolutePath() + UrlConst.POPTEMPLEURL + "js/";
        }
        PlatForm.copyPopFile(sourceFileUrlJsp, model.getTableName(), coluName, "JSP"); //复制jsp模板
        PlatForm.copyPopFile(sourceFileUrlJs, model.getTableName(), coluName, "JS"); //复制js模板
    }

    /**
     * * <p>Title: 弹出的树模型</p>
     *
     * @author : xiaoliu
     * @date :2016年8月10日上午9:09:25
     */
    public static void copyTreeFile(Model model, String coluName) {
        String sourceFileUrlJsp = PlatForm.getAbsolutePath() + UrlConst.TREEURL;  //jsp模板存放的路径
        String sourceFileUrlJs = PlatForm.getAbsolutePath() + UrlConst.TREEURL + "js/";  //jsp模板存放的路径
        PlatForm.copyTreeFile(sourceFileUrlJsp, model.getTableName(), coluName, "JSP"); //复制jsp模板
        PlatForm.copyTreeFile(sourceFileUrlJs, model.getTableName(), coluName, "JS"); //复制js模板
    }

    /**
     * 查找生成后的jsp  js模板的路径
     *
     * @param surveyType 业务类型(表名)
     * @param operType   操作类型  页面的_后的名字
     * @param pageType   js 或者jsp文件
     * @return
     */
    public static String getFilePath(String surveyType, String operType, String pageType) {
        String targetFilePath = "";
        String webrootUrl = PlatForm.getAbsolutePath();  //获取webroot的url  项目的部署路径
        if ("js".equals(pageType)) {
            targetFilePath = webrootUrl + "am/" + surveyType + "/js/" + surveyType + "_" + operType + "." + pageType; //获取js文件
        } else {
            targetFilePath = webrootUrl + "am/" + surveyType + "/" + surveyType + "_" + operType + "." + pageType; //拼写出要写入的文件路径   ROOT/am/AM_T001/AM_T001_add.jsp
        }
        return targetFilePath;
    }

    //二次开发页面的模板
//	public static String getSecondaryFilePath(String surveyType,String operType,String pageType){
//		String targetFilePath="";
//		 String webrootUrl=PlatForm.getAbsolutePath();  //获取webroot的url  项目的部署路径
//		 if("js".equals(pageType)){
//			 targetFilePath=webrootUrl+"secondary/wanda/"+surveyType+"/js/"+surveyType+"_"+operType+"."+pageType; //获取js文件
//		 }
//		return targetFilePath;
//	}

    public static String getModelPath() {
        String filePath = PlatForm.getAbsolutePath() + "error_text";
        File file = new File(filePath);
        //判断文件夹是否存在，不存在则创建
        if (!file.exists())
            file.mkdir();
        return filePath;
//		return "";
    }

    public static String getFilePath() {
        String filePath = PlatForm.getAbsolutePath() + "file";
        File file = new File(filePath);
        //判断文件夹是否存在，不存在则创建
        if (!file.exists())
            file.mkdir();
        return filePath;
//		return "";
    }

    public static String getTemplatePath() {
        return PlatForm.getAbsolutePath() + "WEB-INF/doc/dataTemplate";
//		return "";
    }

    /**
     * 查找生成后的jsp  js模板的路径
     *
     * @param surveyType 业务类型(表名)
     * @param operType   操作类型  页面的_后的名字
     * @param pageType   js 或者jsp文件
     * @return
     */
    public static String getDetailFilePath(String surveyType, String operType, String pageType) {
        String targetFilePath = "";
        String webrootUrl = PlatForm.getAbsolutePath();  //获取webroot的url  项目的部署路径
        if ("js".equals(pageType)) {
            targetFilePath = webrootUrl + "am/" + surveyType + "/js/" + surveyType + "_" + operType + "." + pageType; //获取js文件
        } else {
            targetFilePath = webrootUrl + "am/" + surveyType + "/" + surveyType + "_" + operType + "." + pageType; //拼写出要写入的文件路径   ROOT/am/AM_T001/AM_T001_add.jsp
        }
        return targetFilePath;
    }

    /**
     * 根据jsp页面路径获取jsp里的内容
     */
    public static String getTmpJspContent(String readFilePath) {
        File file = new File(readFilePath);  //根据路径读取文件
        StringBuilder buffer = new StringBuilder();
        String nextLine = "";
        try {
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
            BufferedReader bf = new BufferedReader(isr);
            while ((nextLine = bf.readLine()) != null) {
                buffer.append(nextLine);  //将文件里的内容转为字符串
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    /**
     * 将字符串写入jsp目标文件
     *
     * @param str            输入的字符串
     * @param targetFilePath 目标文件路径
     * @throws IOException
     */
    public static void writeInJsp(String str, String targetFilePath) throws IOException {
        OutputStreamWriter outWrite = null;
        try {
//        	outWrite = new OutputStreamWriter(new FileOutputStream(new File(targetFilePath)),"UTF-8");
            outWrite = new OutputStreamWriter(new FileOutputStream(targetFilePath), "UTF-8");// 新建文件输出流并对它进行缓冲
            outWrite.write(str);
            outWrite.flush();// 刷新此缓冲的输出流
        } finally {
            // 关闭流
            if (outWrite != null)
                outWrite.close();
        }
    }

    public static String spellNgShow(List<String> list, List<AttrConfig> attributeRadioList, List<AttrConfig> attributeCheckboxList) {
        StringBuilder sb = new StringBuilder();
        if (null == attributeRadioList || null == attributeCheckboxList)
            sb.append("    if(check()){$RN$");
        for (int i = 0; i < list.size(); i++) {
            sb.append("        if(check" + list.get(i) + "()){ $RN$");
            if (i == list.size() - 1) {
//				if("0".equals(model.getModelType())){//表示主数据
//					sb.append("       var flag = checkAddForum(); $RN$");
//					sb.append("           if(flag){ $RN$");
//					sb.append("              submitData(); $RN$");
//					sb.append("           }$RN$");
//				}else{//表示字典表
                sb.append("             submitData(); $RN$");
//				}
            }
        }
        for (int i = 0; i < list.size(); i++) {
            sb.append("         } $RN$");
        }
        if (null == attributeRadioList || null == attributeCheckboxList)
            sb.append("       }$RN$");
        return sb.toString().replace("$RN$", "\r\n");
    }

//    public static String spellNgShow(Model model,List<String> list,List<AttrConfig> attributeRadioList,List<AttrConfig> attributeCheckboxList){
//		StringBuilder sb=new StringBuilder();
//		if(null==attributeRadioList || null==attributeCheckboxList)
//		    sb.append("    if(check()){$RN$");
//		for (int i = 0; i < list.size(); i++) {
//			sb.append("        if(check"+list.get(i)+"()){ $RN$");
//			if(i==list.size()-1){
//				if("0".equals(model.getModelType())){//表示主数据
//					sb.append("       var flag = checkAddForum(); $RN$");
//					sb.append("           if(flag){ $RN$");
//					sb.append("              submitData(); $RN$");
//					sb.append("           }$RN$");
//				}else{//表示字典表
//					 sb.append("             submitData(); $RN$");
//				}
//			  }
//		}
//		for (int i = 0; i <list.size(); i++) {
//			sb.append("         } $RN$");
//		}
//		if(null==attributeRadioList || null==attributeCheckboxList)
//		sb.append("       }$RN$");
//		return sb.toString().replace("$RN$", "\r\n");
//	}

    /**
     * 生成新增  编辑页面的点击下拉框加载的方法
     *
     * @param operType -- 传递的操作
     */
    public static String spellSelectClick(String operType, Model model, Map<String, Map<String, AttrConfig>> selectMap) {
        StringBuilder sb = new StringBuilder();
        // selectMap -- 存储了本模型下所有的数据类型为下拉框的 attrconfig对象
        for (String key : selectMap.keySet()) {
            Map<String, AttrConfig> valMap = selectMap.get(key);
            //current当前的级联列，有可能是一级级联，也可能是二级级联
            AttrConfig current = valMap.get("current");//当前列
            //这是获取级联列的 关联列，有可能是下拉框，也有可能是单选按钮，或者弹出框
            AttrConfig prefix = valMap.get("prefix");//上一列
            //获取级联列的下一级联，有可能是空，也有可能是一个级联selectList
            AttrConfig sufix = valMap.get("sufix");//下一列
            // 当前点击列 【省】
            String col_current = current.getAttrColumn().toLowerCase();
            // 级联列 【国家】
            String col_cascade_prefix = prefix.getAttrColumn().toLowerCase();
            if (sufix != null) {//说明是一级级联----eg:省份
                // 被级联列 【市】
                String col_cascade_sufix = sufix.getAttrColumn().toLowerCase();
                // 获取关联的列名
//				String guanL = col_cascade_prefix;
                if ("2".equals(current.getModuleType())) {//当前列，是下拉框的一级级联列
                    sb.append("       $scope.selClick" + col_current + "=function (){ $RN$");
                    sb.append("           var aa=''; $RN$");
//					sb.append("           var guanL=''; $RN$");
                    if ("edit".equals(operType) || "updateEdit".equals(operType) || "treeTabEdit".equals(operType) || "treeTabUpdateEdit".equals(operType)) {
                        if ("checkBoxType".equals(current.getAttrType())) {
                            sb.append("       aa=checkVal" + col_current + "(); $RN$");
                        } else {
                            sb.append("       aa=$scope." + col_current + "; $RN$");
//							sb.append("       guanL=$scope." + col_cascade_prefix + "; $RN$");
                        }
                    } else {
                        // 查询出来的是关联列是否选择，去判断级联列是否加载数据
                        sb.append("           aa=$scope." + col_current + "; $RN$");
//						sb.append("           guanL=$scope." + guanL + "; $RN$");
                    }
                    sb.append("         if(aa){ $RN$").append("	            $http({ $RN$");
                    sb.append("	                       url : basePath+'/genJsp/getSelectData', $RN$");
                    sb.append("	                       method : 'POST', $RN$");
                    sb.append("                        params : { $RN$");
                    sb.append("                        modelId: '" + model.getId() + "', attrColumn:'" + col_cascade_sufix.toUpperCase() + "', columnValue: aa , isCascad :'yes' $RN$");
                    sb.append("                } $RN$");
                    sb.append("	           }).success(function(data, header, config, status) { $RN$");
                    sb.append("                  $scope." + col_cascade_sufix + "s= data.data; $RN$");
                    sb.append("            }).error(function(data, header, config, status) { $RN$");
                    sb.append("                 toastr.error('数据加载失败！'); $RN$");
                    sb.append("	           }); $RN$");
                    sb.append("         }else{ $RN$");
                    sb.append("	                 toastr.warning('请先选择【" + current.getAttrName() + "】级联列对应的关联列【" + prefix.getAttrName() + "】的值！'); $RN$");
                    sb.append("	                 return; $RN$");
                    sb.append("         } $RN$").append("} $RN$  $RN$");

                }
                if ("2".equals(sufix.getModuleType())) {//----城市
                    sb.append("     $scope.selClick" + col_cascade_sufix + "=function (){ $RN$");
                    sb.append("                var aa=''; $RN$");
                    if ("edit".equals(operType) || "updateEdit".equals(operType) || "treeTabEdit".equals(operType) || "treeTabUpdateEdit".equals(operType)) {
                        if ("checkBoxType".equals(sufix.getAttrType())) {
                            sb.append("         aa=checkVal" + col_cascade_sufix + "(); $RN$");
                        } else {
                            sb.append("         aa=$scope." + col_current + "; $RN$");
                        }
                    } else {
                        // 查询出来的是关联列是否选择，去判断级联列是否加载数据
                        sb.append("             aa=$scope." + col_current + "; $RN$");
                    }
                    sb.append("          if(aa){ $RN$");
                    sb.append("          }else{ $RN$").append("          toastr.warning('请先选择【" + sufix.getAttrName() + "】级联列对应的级联列【" + current.getAttrName() + "】的值！'); $RN$");
                    sb.append("	                 return; $RN$");
                    sb.append("          } $RN$").append("} $RN$  $RN$");
                }

                // 关联-级联关系
                if ("1".equals(prefix.getModuleType())) {// 查询出关联列--c_008
                    if ("selectList".equals(prefix.getAttrType())) {//这说明级联列的关连列是下拉框
                        sb.append("      $scope.selClick" + col_cascade_prefix + "=function () { $RN$");
                        sb.append("                 var aa=''; $RN$");
                        if ("edit".equals(operType) || "updateEdit".equals(operType)) {
                            if ("checkBoxType".equals(prefix.getAttrType())) {
                                sb.append("        aa=checkVal" + col_cascade_prefix + "(); $RN$");
                            } else {
                                sb.append("        aa=$scope." + col_cascade_prefix + "; $RN$");
//								sb.append("        guanL=$scope." + col_cascade_prefix + "; $RN$");
                            }
                        } else {
                            // 查询出来的是关联列是否选择，去判断级联列是否加载数据
                            sb.append("            aa=$scope." + col_cascade_prefix + "; $RN$");
                        }
                        sb.append("	       $http({ $RN$");
                        sb.append("	               url : basePath+'/genJsp/getSelectData', $RN$");
                        sb.append("	               method : 'POST', $RN$");
                        sb.append("                params : { $RN$");
                        sb.append("                modelId: '" + model.getId() + "', attrColumn:'" + col_current.toUpperCase() + "', columnValue:aa , isCascad :'yes' $RN$");
                        sb.append("             } $RN$");
                        sb.append("	          }).success(function(data, header, config, status) { $RN$");
                        sb.append("		           $scope." + col_current + "s= data.data; $RN$");
                        sb.append("		           $scope." + col_cascade_sufix + "s=null; $RN$");
                        sb.append("           }).error(function(data, header, config, status) { $RN$");
                        sb.append("		           toastr.error('数据加载失败！'); $RN$");
                        sb.append("	          }); $RN$").append("} $RN$  $RN$");
                        ;

                    } else if ("radioType".equals(prefix.getAttrType())) {//如果级联列的 关连列是单选按钮
                        //---以后补充
                        sb.append("   $scope.input" + col_cascade_prefix + "ValueIsChanged = function(eId){ $RN$");
                        // 获取跟关联有关的级联
                        sb.append("                 var aa=''; $RN$");
                        if ("edit".equals(operType) || "updateEdit".equals(operType)) {
                            if ("checkBoxType".equals(prefix.getAttrType())) {
                                sb.append("         aa=checkVal" + col_cascade_prefix + "(); $RN$");
                            } else {
                                sb.append("         aa=$scope." + col_cascade_prefix + "; $RN$");
//									sb.append("         guanL=$scope." + col_cascade_prefix + "; $RN$");
                            }
                        } else {
                            // 查询出来的是关联列是否选择，去判断级联列是否加载数据
                            sb.append("             aa=$scope." + col_cascade_prefix + "; $RN$");
                        }
                        sb.append("	        $http({ $RN$");
                        sb.append("	              url : basePath+'/genJsp/getSelectData', $RN$");
                        sb.append("	              method : 'POST', $RN$");
                        sb.append("               params : { $RN$");
                        sb.append("               modelId: '" + model.getId() + "', attrColumn:'" + col_current.toUpperCase() + "', columnValue:aa , isCascad :'yes' $RN$");
                        sb.append("             } $RN$");
                        sb.append("	          }).success(function(data, header, config, status) { $RN$");
                        sb.append("		            $scope." + col_current + "s= data.data; $RN$");
                        sb.append("           }).error(function(data, header, config, status) { $RN$");
                        sb.append("		           toastr.error('数据加载失败！'); $RN$");
                        sb.append("	          }); $RN$");
                        sb.append("          $event = document.getElementById(''+eId+''); $RN$");
                        sb.append("          settings_isChanged[''+name] = false; $RN$");
                        sb.append("           if($event.type == 'radio'){ $RN$");
                        sb.append("              if($event.checked != $event.defaultChecked){ $RN$");
                        sb.append("                  settings_isChanged[''+name] = true;$RN$");
                        sb.append("               }$RN$");
                        sb.append("              if(isChanged()){$RN$");
                        sb.append("                 $('#saveButton').attr('disabled',false);$RN$");
                        sb.append("              }else{$RN$");
                        sb.append("                $('#saveButton').attr('disabled',true);$RN$");
                        sb.append("             }$RN$");
                        sb.append("       }$RN$");
                        sb.append("     } $RN$");
                        sb.append("$RN$");
                    }
                }
            } else {//存在两种情况--1.例如，出出来的当前列是c_016二级级联，还有一种就是，没有二级级联
                //如果是这种情况，只需要判断上级是不是prefix是   级联  还是 关联
                if ("1".equals(prefix.getModuleType())) {//是关联关系，说明是二级级联关系=========关联-级联关系
                    if ("selectList".equals(prefix.getAttrType())) {//这说明级联列的关连列是下拉框
                        sb.append("            $scope.selClick" + col_cascade_prefix + "=function (){ $RN$");
                        // 获取跟关联有关的级联
                        sb.append("                 var aa=''; $RN$");
                        if ("edit".equals(operType) || "updateEdit".equals(operType)) {
                            if ("checkBoxType".equals(prefix.getAttrType())) {
                                sb.append("         aa=checkVal" + col_cascade_prefix + "(); $RN$");
                            } else {
                                sb.append("         aa=$scope." + col_cascade_prefix + "; $RN$");
//									sb.append("         guanL=$scope." + col_cascade_prefix + "; $RN$");
                            }
                        } else {
                            // 查询出来的是关联列是否选择，去判断级联列是否加载数据
                            sb.append("             aa=$scope." + col_cascade_prefix + "; $RN$");
                        }
                        sb.append("	        $http({ $RN$");
                        sb.append("	              url : basePath+'/genJsp/getSelectData', $RN$");
                        sb.append("	              method : 'POST', $RN$");
                        sb.append("               params : { $RN$");
                        sb.append("               modelId: '" + model.getId() + "', attrColumn:'" + col_current.toUpperCase() + "', columnValue:aa , isCascad :'yes' $RN$");
                        sb.append("             } $RN$");
                        sb.append("	          }).success(function(data, header, config, status) { $RN$");
                        sb.append("		            $scope." + col_current + "s= data.data; $RN$");
                        sb.append("           }).error(function(data, header, config, status) { $RN$");
                        sb.append("		           toastr.error('数据加载失败！'); $RN$");
                        sb.append("	          }); $RN$");
                        sb.append("       }$RN$");
                    } else if ("radioType".equals(prefix.getAttrType())) {//如果级联列的 关连列是单选按钮
                        //---以后补充
                        sb.append("  $scope.input" + col_cascade_prefix + "ValueIsChanged = function(eId){ $RN$");
                        // 获取跟关联有关的级联
                        sb.append("                 var aa=''; $RN$");
                        if ("edit".equals(operType) || "updateEdit".equals(operType)) {
                            if ("checkBoxType".equals(prefix.getAttrType())) {
                                sb.append("         aa=checkVal" + col_cascade_prefix + "(); $RN$");
                            } else {
                                sb.append("         aa=$scope." + col_cascade_prefix + "; $RN$");
//									sb.append("         guanL=$scope." + col_cascade_prefix + "; $RN$");
                            }
                        } else {
                            // 查询出来的是关联列是否选择，去判断级联列是否加载数据
                            sb.append("             aa=$scope." + col_cascade_prefix + "; $RN$");
                        }
                        sb.append("	        $http({ $RN$");
                        sb.append("	              url : basePath+'/genJsp/getSelectData', $RN$");
                        sb.append("	              method : 'POST', $RN$");
                        sb.append("               params : { $RN$");
                        sb.append("               modelId: '" + model.getId() + "', attrColumn:'" + col_current.toUpperCase() + "', columnValue:aa  , isCascad :'yes' $RN$");
                        sb.append("             } $RN$");
                        sb.append("	          }).success(function(data, header, config, status) { $RN$");
                        sb.append("		            $scope." + col_current + "s= data.data; $RN$");
                        sb.append("           }).error(function(data, header, config, status) { $RN$");
                        sb.append("		           toastr.error('数据加载失败！'); $RN$");
                        sb.append("	          }); $RN$");
                        sb.append("           $event = document.getElementById(''+eId+''); $RN$");
                        sb.append("           settings_isChanged[''+name] = false; $RN$");
                        sb.append("           if($event.type == 'radio'){ $RN$");
                        sb.append("              if($event.checked != $event.defaultChecked){ $RN$");
                        sb.append("                 settings_isChanged[''+name] = true;$RN$");
                        sb.append("              }$RN$");
                        sb.append("              if(isChanged()){$RN$");
                        sb.append("                  $('#saveButton').attr('disabled',false);$RN$");
                        sb.append("             }else{$RN$");
                        sb.append("              $('#saveButton').attr('disabled',true);$RN$");
                        sb.append("             }$RN$");
                        sb.append("         }$RN$");
                        sb.append("       } $RN$");
                        sb.append("$RN$");
//							sb.append("       }$RN$"); 
                    }

                    if ("2".equals(current.getModuleType())) {//----城市
                        sb.append("           $scope.selClick" + col_current + "=function (){ $RN$");
                        sb.append("               var aa=''; $RN$");
                        if ("edit".equals(operType) || "updateEdit".equals(operType)) {
                            if ("checkBoxType".equals(current.getAttrType())) {
                                sb.append("           aa=checkVal" + col_current + "(); $RN$");
                            } else {
                                sb.append("           aa=$scope." + col_current + "; $RN$");
                            }
                        } else {
                            // 查询出来的是关联列是否选择，去判断级联列是否加载数据
                            sb.append("               aa=$scope." + col_current + "; $RN$");
                        }
                        sb.append("          if(aa){ $RN$");
                        sb.append("          }else{ $RN$").append("               toastr.warning('请先选择【" + current.getAttrName() + "】级联列对应的关联列【" + prefix.getAttrName() + "】的值！'); $RN$");
                        sb.append("	                 return; $RN$");
                        sb.append("          } $RN$").append("} $RN$  $RN$");
                    }
                }
            }
        }
        return sb.toString().replace("$RN$", "\r\n");
    }

    /**
     * 生成新增  编辑页面的校验方法
     * 校验是否为空  大于  小于和不等于  等于
     */
    public static String createCheckFunction(String operType, List<AttrConfig> attributeRadioList, List<AttrConfig> attributeCheckboxList) {
        StringBuilder functionStr = new StringBuilder();
        functionStr.append("   function check(){ $RN$");
        functionStr.append("	   var flag=true; $RN$");

        if (null != attributeRadioList && attributeRadioList.size() != 0) {
            for (int i = 0; i < attributeRadioList.size(); i++) {
                functionStr.append("        if(null==$scope." + attributeRadioList.get(i).getAttrColumn().toLowerCase() + " || ''==$scope." + attributeRadioList.get(i).getAttrColumn().toLowerCase() + "){ $RN$")
                        .append("             toastr.warning('" + attributeRadioList.get(i).getAttrName() + "不能为空!'); $RN$")
                        .append("             flag=false; $RN$").append("       } $RN$");
            }
        }

        if (null != attributeCheckboxList && attributeCheckboxList.size() != 0) {
            for (int i = 0; i < attributeCheckboxList.size(); i++) {
                if ("add".equals(operType) || "treeTabAdd".equals(operType)) {
                    functionStr.append("       if(!$scope." + attributeCheckboxList.get(i).getAttrColumn().toLowerCase() + "){ $RN$");
                    functionStr.append("           flag=true; $RN$").append("} $RN$");
                } else {
                    functionStr.append("       if(null == checkVal" + attributeCheckboxList.get(i).getAttrColumn().toLowerCase() + "() || ''==checkVal" + attributeCheckboxList.get(i).getAttrColumn().toLowerCase() + "()){ $RN$")
                            .append("                        toastr.warning('" + attributeCheckboxList.get(i).getAttrName() + "不能为空!'); $RN$")
                            .append("                        flag=false; $RN$").append("    } $RN$");
                }
            }
        }
        functionStr.append("          return flag; $RN$ } $RN$");
        return functionStr.toString().replace("$RN$", "\r\n");
    }

    public static String formatSelectCol(String colValue) {
        String resStr = "";
        String[] split = colValue.split(",");
        for (String str : split) {
            if ("" == resStr) {
                resStr = str.split(":")[1];
            } else {
                resStr += "," + str.split(":")[1];
            }
        }
        return resStr.substring(0, resStr.length() - 1);
    }

    /**
     * 将空格和换行替换 jsp页面替换
     * （1.目前列表申请用到啦）
     * @return
     */
//	public static String replaceFormat(String fileStr, Model model,String operType){
//		String surveyType = model.getTableName();
//		fileStr=fileStr.replace("@R#", "\r\n");  //替换换行
//		fileStr=fileStr.replace("{modelId}", surveyType.split("_")[1]);  //替换按钮权限的modelId
//		fileStr=fileStr.replace("{shiroName}", surveyType);  //替换按钮权限的modelId
//		if("update".equals(operType) ||"treeTabUpdate".equals(operType)){
//			fileStr=fileStr.replace("{tableId}", surveyType +TableConst.MODIFYSUFFIX);  //surveyType+"_update");
//		}else if("updateHis".equals(operType) ||"treeTabUpdateHis".equals(operType)){
//			fileStr=fileStr.replace("{tableId}", surveyType+"_updateHis");
//		}else{
//			fileStr=fileStr.replace("{tableId}", surveyType);
//		}
//		fileStr=fileStr.replace("{MainColumn}",JspUtil.spellColumn(model,Type.MAIN));
//		fileStr=fileStr.replace("{UpdateHisColumn}", JspUtil.spellColumn(model,Type.UPDATEHIS));
//		fileStr=fileStr.replace("{ListColumn}", JspUtil.spellColumn(model,Type.QUERY));
//		fileStr=fileStr.replace("{ShColumn}",JspUtil.spellColumn(model,Type.APPROVE));
//		fileStr=fileStr.replace("{UpdateColumn}",JspUtil.spellColumn(model,Type.UPDATE));
//		fileStr=fileStr.replace("{includeJs}", surveyType+"/js/"+surveyType+"_"+operType+".js");//替换table id
//		return fileStr;
//	}

    /**
     * 将空格和换行替换 jsp页面替换
     * （1.目前列表申请用到啦）
     *
     * @return
     */
    public static String replaceListFormat(String fileStr, Model model, String operType) {
        String surveyType = model.getTableName();
        fileStr = fileStr.replace("@R#", "\r\n");  //替换换行
        fileStr = fileStr.replace("{modelId}", surveyType.split("_")[1]);  //替换按钮权限的modelId
        fileStr = fileStr.replace("{shiroName}", surveyType);  //替换按钮权限的modelId
        if ("update".equals(operType)) {
            fileStr = fileStr.replace("{tableId}", surveyType + TableConst.MODIFYSUFFIX);  //surveyType+"_update");
        } else if ("updateHis".equals(operType) || "treeTabUpdateHis".equals(operType)) {
            fileStr = fileStr.replace("{tableId}", surveyType + "_updateHis");
        } else {
            fileStr = fileStr.replace("{tableId}", surveyType);
        }
        fileStr = fileStr.replace("{includeJs}", surveyType + "/js/" + surveyType + "_" + operType + ".js");//替换table id
        return fileStr;
    }

    public static String replaceTreeFormat(String fileStr, Model model, String operType) {
        String surveyType = model.getTableName();
        fileStr = fileStr.replace("@R#", "\r\n");  //替换换行
        fileStr = fileStr.replace("{modelId}", surveyType.split("_")[1]);  //替换按钮权限的modelId
        fileStr = fileStr.replace("{shiroName}", surveyType);  //替换按钮权限的modelId
        if ("treeTabUpdate".equals(operType) || "update".equals(operType)) {
            fileStr = fileStr.replace("{tableId}", surveyType + TableConst.MODIFYSUFFIX);  //surveyType+"_update");

        } else if ("updateHis".equals(operType) || "treeTabUpdateHis".equals(operType)) {
            fileStr = fileStr.replace("{tableId}", surveyType + "_updateHis");
        } else {
            fileStr = fileStr.replace("{tableId}", surveyType);
        }
        if ("1".equals(model.getClassType())) {//“1”==表示是父子树   “2”==表示分类是 “0”==表示列表
            fileStr = fileStr.replace("{operColumnRep}", "<input type='hidden' id='operColumn' name='operColumn' ng-model='operColumn' value='<%= request.getParameter(\"operColumn\")%>'>");
//			<input type="hidden" name="operColumn" id="operColumn"  ng-model="operColumn"  value="<%=request.getParameter("operColumn") %>" />
        } else if ("2".equals(model.getClassType())) {
            fileStr = fileStr.replace("{operColumnRep}", "");
        }
        fileStr = fileStr.replace("{UpdateHisColumn}", JspUtil.spellColumn(model, Type.UPDATEHIS));
        fileStr = fileStr.replace("{ListColumn}", JspUtil.spellColumn(model, Type.QUERY));
        fileStr = fileStr.replace("{ShColumn}", JspUtil.spellColumn(model, Type.APPROVE));
        fileStr = fileStr.replace("{UpdateColumn}", JspUtil.spellColumn(model, Type.UPDATE));
        fileStr = fileStr.replace("{MainColumn}", JspUtil.spellColumn(model, Type.MAIN));
        fileStr = fileStr.replace("{includeJs}", surveyType + "/js/" + surveyType + "_" + operType + ".js");//替换table id
        return fileStr;
    }

    /**
     * 将空格和换行替换 jsp页面替换
     *
     * @return
     */
    public static String replaceListDetailFormat(Model model, String fileStr, String surveyType, String operType) {
        fileStr = fileStr.replace("@R#", "\r\n");  //替换换行
        if ("0".equals(model.getClassType()) && !StringUtils.isBlank(model.getMaintableId()))
            fileStr = fileStr.replace("{mainIdInput}", " <input type='hidden'  id='mainId'  value='<%= request.getParameter(\"mainId\")%>'>");
        else
            fileStr = fileStr.replace("{mainIdInput}", "");
        if ("update".equals(operType) || "treeTabUpdate".equals(operType)) {
            fileStr = fileStr.replace("{tableId}", surveyType + TableConst.MODIFYSUFFIX);  //surveyType+"_update");
        } else if ("updateHis".equals(operType) || "treeTabUpdateHis".equals(operType)) {
            fileStr = fileStr.replace("{tableId}", surveyType + "_updateHis");
        } else if ("applyDetail".equals(operType)) {//如果是详情页面
            fileStr = fileStr.replace("{modelId}", model.getId());
            fileStr = fileStr.replace("{tableId}", surveyType);
            fileStr = fileStr.replace("{includeJs}", surveyType + "/js/" + surveyType + "_" + operType + ".js");
        } else {
            fileStr = fileStr.replace("{tableId}", surveyType);
        }
        fileStr = fileStr.replace("{includeJs}", surveyType + "/js/" + surveyType + "_" + operType + ".js");//替换table id
        return fileStr;
    }


    /**
     * * <p>Title: </p>
     * <p>Company:@param fileStr
     * <p>Company:@param model
     * <p>Company:@param operType
     * <p>Company:@return </p>
     *
     * @author : xiaoliu
     * @date :2016年12月14日上午9:35:29
     */
    public static String replaceTreeTabMainFormat(String fileStr, Model model, Model fenModel, String operType, List<AttrConfig> configLst) {

        String tableName = model.getTableName();
        fileStr = fileStr.replace("@R#", "\r\n");  //替换换行

        if ("2".equals(model.getClassType())) {//分类树
            if (model.getMaintableId() != null) {
                fileStr = fileStr.replace("{tableName}", TableConst.TABLEPREFIX + model.getMaintableId());
                fileStr = fileStr.replace("{tableTree}", TableConst.TABLEPREFIX + model.getMaintableId() + "Tree");
//				    fileStr=fileStr.replace("{treeName}", model.getModelName());
            } else {
                fileStr = fileStr.replace("{tableName}", tableName)
                        .replace("{tableTree}", tableName + "Tree");
//					fileStr=fileStr.replace("{treeName}", model.getModelName());
            }
        } else if ("1".equals(model.getClassType())) {//如果是父子树
            fileStr = fileStr.replace("{tableName}", tableName);
            fileStr = fileStr.replace("{tableTree}", tableName + "Tree");
//		         fileStr=fileStr.replace("{treeName}", model.getModelName());
        }
        fileStr = fileStr.replace("{ulTreeReplace}", spellUlTreeReplace(model, fenModel, operType, configLst));
        //fileStr=fileStr.replace("{ulTreeJsReplace}",spellUlTreeJsReplace(model,fenModel,operType,configLst));
        fileStr = fileStr.replace("{tableFrame}", tableName + "Frame");
        fileStr = fileStr.replace("{includeJs}", tableName + "/js/" + tableName + "_" + operType + ".js");//替换table id
        return fileStr;
    }


    public static String replaceTreeTabFormat(String fileStr, Model model, String operType) {
        String tableName = model.getTableName();
        fileStr = fileStr.replace("@R#", "\r\n")  //替换换行
                .replace("{modelId}", model.getId())  //替换按钮权限的modelId
                .replace("{tableId}", tableName);//替换table id String surveyType
        if ("2".equals(model.getClassType())) {
            if (model.getMaintableId() != null) {
                fileStr = fileStr.replace("{mainTableName}", TableConst.TABLEPREFIX + model.getMaintableId());

            } else {
                fileStr = fileStr.replace("{mainTableName}", tableName);
            }
        } else {
            fileStr = fileStr.replace("{mainTableName}", tableName);
        }
        if ("1".equals(model.getClassType())) {//“1”==表示是父子树   “2”==表示分类是 “0”==表示列表
            fileStr = fileStr.replace("{operColumnRep}", "<input type='hidden' id='operColumn' name='operColumn' ng-model='operColumn' value='<%= request.getParameter(\"operColumn\")%>'>");
//			<input type="hidden" name="operColumn" id="operColumn"  ng-model="operColumn"  value="<%=request.getParameter("operColumn") %>" />
        } else if ("2".equals(model.getClassType())) {
            fileStr = fileStr.replace("{operColumnRep}", "");
        }
        fileStr = fileStr.replace("{tableName}", tableName);
        fileStr = fileStr.replace("{MainColumn}", JspUtil.spellColumn(model, Type.MAIN));
        fileStr = fileStr.replace("{ApplyColumn}", JspUtil.spellColumn(model, Type.APPLY));
        fileStr = fileStr.replace("{ListColumn}", JspUtil.spellColumn(model, Type.QUERY));
        fileStr = fileStr.replace("@R#", "\r\n");
        fileStr = fileStr.replace("{includeJs}", tableName + "/js/" + tableName + "_" + operType + ".js");//替换table id
        return fileStr;
    }

    /**
     * 将空格和换行替换 jsp页面替换
     *
     * @return
     */
    public static String replacePopFormat(String fileStr, String surveyType, String sourceSurveyType, String popColum, String operType) {
        fileStr = fileStr.replace("@R#", "\r\n");  //替换换行
        if ("popList".equals(operType)) {
            fileStr = fileStr.replace("{tableId}", sourceSurveyType + "_" + popColum + "_pop")
                    .replace("{popDiv}", sourceSurveyType + "_" + popColum + "_toorBar")
                    .replace("{includeJs}", surveyType + "/js/" + surveyType + "_" + popColum + operType + ".js");
        } else {
            fileStr = fileStr.replace("{tableId}", surveyType + "_bgPop")
                    .replace("{popDiv}", surveyType + "_bgToorBar")
                    .replace("{includeJs}", surveyType + "/js/" + surveyType + "_" + operType + ".js");
        }
        return fileStr;
    }

    //第一次使用，弹出tree用到此方法
    public static String replaceTreeFormat(String fileStr, Model model, String sourceSurveyType, String operType, String fileName) {
        String surveyType = model.getTableName();
        fileStr = fileStr.replace("@R#", "\r\n")  //替换换行
                .replace("{treeId}", sourceSurveyType + operType + "tree")
//			.replace("{treeName}",model.getModelName())
                .replace("{tableName}", sourceSurveyType)//替换table id//替换成dataSourceTable
                .replace("{treeDiv}", sourceSurveyType + operType)
                .replace("{includeJs}", surveyType + "/js/" + surveyType + "_" + operType + fileName + ".js");
        return fileStr;
    }

    /**
     * 每个列表页面的js都要替换的内容  js页面替换
     */
    public static String replaceStr(String readFilePath, Model model, String operType) {
        String script = "";
        try {
            script = JspUtil.getTmpJspContent(readFilePath)  //根据路径获取自动生成的模板内容
                    .replace("{tableId}", model.getTableName()) //表的id
                    .replace("{controlUrl}", UrlConst.LISTURL) //查询的controller地址
                    .replace("@R#", "\r\n") //替换换行
                    .replace("{modelId}", String.valueOf(model.getId())) //替换modelid
                    .replace("{surveyType}", model.getTableName()) //替换业务类型
                    .replace("{operType}", operType); //替换操作类型
        } catch (Exception e) {
            e.printStackTrace();
        }
        return script;
    }

    /**
     * 每个列表页面的pop页面替换
     */
    public static String getBgPopColumn(Model model) {
        StringBuilder sb = new StringBuilder();
        try {
            if ("1".equals(model.getClassType())) {//如果是父子树
                sb.append(" <input type='hidden' id='bgPopPid' value='<%= request.getParameter(\"UpdatePid\")%>'> ");
            } else if ("2".equals(model.getClassType())) {//如果是分类树
                sb.append("<input type='hidden' id='bgPopColumn' value='<%= request.getParameter(\"UpdateColumn\")%>'>");
            } else {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 生成js校验控制显示隐藏列必填的方法
     *
     * @param columnName检验的列
     * @param map                               哪个值显示必填的哪几列
     * @param showHideColumns全部受显示隐藏控制的列，用来将值去掉
     * @return
     */
    public static String checkNgShow(String columnName, Map<String, String> mapisNotNull, String selectedStr) {

        Map<String, String> map = splitCase(selectedStr); //将关联的值和列拆分成map
        String showHideColumns = allCaseColumn(selectedStr); //获取所有关联的列
        StringBuilder sb = new StringBuilder();
        List<String> valueLst = new ArrayList<String>();

        sb.append("        function check" + columnName + "(){ $RN$");   //js方法的名字  check+列名
        sb.append("                var flag=true; $RN$");
        sb.append("                var selValue=$scope." + columnName.toLowerCase() + "; $RN$");   //选中的值

        for (String keyAll : map.keySet()) {
            valueLst.add(keyAll);//所有的关联的值
            String caseColumn = mapisNotNull.get(keyAll); //查看这个值有没有必填的关联列
            String controlClumnAll = map.get(keyAll);  //获取这个值控制的列
            String[] columnSp = controlClumnAll.split(","); //按逗号分割取出每一列
            List<String> setColVoid = setVoid(columnSp, showHideColumns);

            if (!"".equals(caseColumn) && null != caseColumn) {
                sb.append("         if(selValue=='" + keyAll + "'){ $RN$"); //if判断
                String controlClumns = mapisNotNull.get(keyAll);  //获取这个值控制的必填的列
                String[] columns = controlClumns.split(","); //按逗号分割取出每一列

                for (String noRelColumn : setColVoid) {
                    sb.append("            $scope." + noRelColumn.toLowerCase() + "=null; $RN$"); //将没有显示出来的属性设为空,避免保存到数据库
                }

                for (int i = 0; i < columns.length; i++) {  //拼写if判断体
                    sb.append("     if(null == $scope." + columns[i].toLowerCase() + " || " + "'' == $scope." + columns[i].toLowerCase() + "){ $RN$");
                    sb.append("               toastr.warning('请填写全部的必填项！') $RN$");
                    sb.append("               flag=false; $RN$");
                    sb.append("               return false; $RN$");
                    if (i != columns.length - 1) {
                        sb.append("  }else ");
                    } else {
                        sb.append("} $RN$ ");
                    }
                }
                sb.append(" } $RN$");
            }
        }

        sb.append("        if(selValue != '" + valueLst.get(0) + "'");
        for (int i = 1; i < valueLst.size(); i++) {
            sb.append("      && selValue!= '" + valueLst.get(i) + "'");
        }
        sb.append("          ){ $RN$ ");
        for (String str : showHideColumns.split(",")) {
            sb.append("         $scope." + str.toLowerCase() + "=null; $RN$");
        }
        sb.append("          } $RN$ if(selValue != '" + valueLst.get(0) + "'){ $RN$");
        String controlClumnAll = map.get(valueLst.get(0));
        String[] columns = controlClumnAll.split(","); //按逗号分割取出每一列
        for (String noRelColumn : columns) {
//					   sb.append("            $("+"#"+noRelColumn.toLowerCase()+").val(''); $RN$");
            sb.append("                  $('#" + noRelColumn.toLowerCase() + "').val(''); $RN$");
            sb.append("            $scope." + noRelColumn.toLowerCase() + "=null; $RN$"); //将没有显示出来的属性设为空,避免保存到数据库
        }

        sb.append("          } $RN$ ");
        for (int i = 1; i < valueLst.size(); i++) {
            sb.append("  if( selValue!= '" + valueLst.get(i) + "'){ $RN$");
            String clumnAll = map.get(valueLst.get(i));
            String[] columnAlls = clumnAll.split(","); //按逗号分割取出每一列
            for (String noRelColumn : columnAlls) {
//				   sb.append("            $("+"#"+noRelColumn.toLowerCase()+").val(''); $RN$");
                sb.append("                  $('#" + noRelColumn.toLowerCase() + "').val(''); $RN$");
                sb.append("            $scope." + noRelColumn.toLowerCase() + "=null; $RN$"); //将没有显示出来的属性设为空,避免保存到数据库
            }
            sb.append("          } $RN$ ");
        }
        sb.append("            return flag; $RN$");
        sb.append("          } $RN$");
        return sb.toString().replace("$RN$", "\r\n");
    }

    public static List<String> setVoid(String[] column, String columns) {
        List<String> columnLst = new ArrayList<String>();
        List<String> columnsLst = new ArrayList<String>();
        for (String col : column) {
            columnLst.add(col);
        }
        for (String col : columns.split(",")) {
            if (!(columnLst.contains(col))) {
                columnsLst.add(col);
            }
        }
        return columnsLst;
    }

    public static Map<String, String> splitCase(String caseAttr) {
        Map<String, String> map = new HashMap<String, String>();
        String[] caseCol = caseAttr.split("@@");
        for (int i = 0; i < caseCol.length; i++) {
            String[] splitCase = caseCol[i].split(":");
            map.put(splitCase[0], splitCase[1]);
        }
        return map;
    }

    /**
     * 所有级联设置的列
     *
     * @param caseAttr
     * @return
     */
    public static String allCaseColumn(String caseAttr) {
        String allColumn = "";
        String[] caseCol = caseAttr.split("@@");
        for (int i = 0; i < caseCol.length; i++) {
            String[] splitCase = caseCol[i].split(":");
            for (String col : splitCase[1].split(",")) {
                if ("".equals(allColumn)) {
                    allColumn = col;
                } else if (allColumn.indexOf(col) == -1 && !("".equals(allColumn))) {
                    allColumn += "," + col;
                }
            }
        }
        return allColumn;
    }

    /**
     * 再次生成页面时删除原来的文件
     *
     * @param workspaceRootPath
     */
    public static void clearFiles(String jspPath) {
        String filePath = PlatForm.getAbsolutePath() + "am/" + jspPath;
        File file = new File(filePath);
        if (file.exists()) {
            deleteFile(file);
        }
    }

    /**
     * 递归循环删除文件夹下面的目录及文件
     *
     * @param file
     */
    private static void deleteFile(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                deleteFile(files[i]);
            }
        }
        file.delete();
    }

    /**
     * 生成新增，编辑，变更页面模型是主表的页面内容
     * 2016/9/21 14:40
     * byr
     */
    public static Map<String, String> spellMainContent(Model mainModel, String operType, List<Model> subModelLst, String backPage) {

        StringBuilder sbHead = new StringBuilder();
        StringBuilder sbEnd = new StringBuilder();
        StringBuilder sbJs = new StringBuilder();
        sbHead.append("           <ul id='myTab' class='nav nav-tabs'> $RN$");
        sbHead.append("                <li class='active'> $RN$");
        sbHead.append("                    <a href='#main' data-toggle='tab'> $RN$");
        sbHead.append(mainModel.getModelName() + "  $RN$");
        sbHead.append("                   </a> $RN$");
        sbHead.append("               </li> $RN$");
        sbEnd.append("       </div> $RN$");
        for (int i = 0; i < subModelLst.size(); i++) {
            Model subModel = subModelLst.get(i);
            sbHead.append("           <li> $RN$");
            sbHead.append("                <a href='#" + subModel.getTableName() + "' data-toggle='tab'> $RN$");
            sbHead.append(subModel.getModelName() + " $RN$").append("</a> $RN$").append("</li> $RN$");

            sbEnd.append("   <div class='tab-pane fade' id='" + subModel.getTableName() + "'> $RN$");
            sbEnd.append("         <iframe id='" + subModel.getTableName() + operType + "Frame' name='" + subModel.getTableName() + operType + "Frame' frameborder='0'  width='100%'> $RN$");
            sbEnd.append("         </iframe> $RN$");
            sbEnd.append("   </div> $RN$");

            sbJs.append("       $('#" + subModel.getTableName() + operType + "Frame').height($(window).height()); $RN$");
            if ("add".equals(operType)) {
                sbJs.append("       $('#" + subModel.getTableName() + operType + "Frame').attr('src'," + "basePath+" + "'/am/" + subModel.getTableName() + "/" + subModel.getTableName() + "_" + backPage + ".jsp'); $RN$");
            } else if ("treeTabAdd".equals(operType)) {
                sbJs.append("       $('#" + subModel.getTableName() + operType + "Frame').attr('src'," + "basePath+" + "'/am/" + subModel.getTableName() + "/" + subModel.getTableName() + "_apply.jsp'); $RN$");
            } else if ("edit".equals(operType) || "updateEdit".equals(operType)) {
                sbJs.append("       $('#" + subModel.getTableName() + operType + "Frame').attr('src'," + "basePath+" + "'/am/" + subModel.getTableName() + "/" + subModel.getTableName() + "_" + backPage + ".jsp?mainId='+$('#id').val()); $RN$");
            } else if ("treeTabEdit".equals(operType)) {
                sbJs.append("       $('#" + subModel.getTableName() + operType + "Frame').attr('src'," + "basePath+" + "'/am/" + subModel.getTableName() + "/" + subModel.getTableName() + "_apply.jsp?mainId='+$('#id').val()); $RN$");
            } else if ("treeTabUpdateEdit".equals(operType)) {
                sbJs.append("       $('#" + subModel.getTableName() + operType + "Frame').attr('src'," + "basePath+" + "'/am/" + subModel.getTableName() + "/" + subModel.getTableName() + "_update.jsp?mainId='+$('#id').val()); $RN$");
            } else {
                //刘晶，动态生成查看详情模块替换
                sbJs.append("   $('#" + subModel.getTableName() + operType + "Frame').attr('src'," + "basePath+" + "'/am/" + subModel.getTableName() + "/" + subModel.getTableName() + "_" + "'+styleOp+'" + "Detail.jsp?mainId='+id+'&style='+style); $RN$");
            }
        }
        sbHead.append("        </ul> $RN$");
        sbHead.append("        <div id='myTabContent' class='tab-content'> $RN$");
        sbHead.append("            <div class='tab-pane fade in active' id='main'> $RN$");

        Map<String, String> res_map = new HashMap<String, String>();
        res_map.put("mainHead", sbHead.toString().replace("$RN$", "\r\n"));
        sbEnd.append("        </div> $RN$");
        res_map.put("mainEnd", sbEnd.toString().replace("$RN$", "\r\n"));
        res_map.put("mainJs", sbJs.toString().replace("$RN$", "\r\n"));
        return res_map;
    }

    /**
     * <p>TODO 父子树或者多视图父子树生成左侧树的方法 </p>
     * <p>@param model
     * <p>@param fenModel
     * <p>@param operType
     * <p>@param configLst
     * <p>@return </p>
     *
     * @author : xiaoliu
     * @date :2017年11月22日上午8:54:47
     */
//	   public static String  spellUlTreeReplace(Model model,Model fenModel,String operType,List<AttrConfig> configLst){//拼写，生成树模板的时候
//		   StringBuilder sb = new StringBuilder();
//		   List<AttrConfig> isPLst = new ArrayList<AttrConfig>();
//		   if(model.getClassType().equals("1")){//如果是父子树
//			   if(configLst.size()>0){
//				   for (int i = 0; i < configLst.size(); i++) {
//					   AttrConfig spleeCon = configLst.get(i);
//					if(1==spleeCon.getIsParentType()){//如果是父子树上下级关系
//						isPLst.add(spleeCon);
//					}
//				 }
//			   }
//			   
//				 /*
//				  * 刘晶  2017-06-22 10:46 在此处添加了新方法
//				  * 
//				  */
//			      sb.append(" <div class='panel-body col-sm-12'> $RN$");
//			      sb.append("    <div class='panel-group'  id='accordion'> $RN$");
//			      
//				 for (int i = 0; i < isPLst.size(); i++) {
//					 AttrConfig isDPLst = isPLst.get(i);
//					
//					 /*
//					  * 刘晶  2017-06-22 10:46 在此处添加了新方法
//					  * 
//					  */
//					 
//					 sb.append("    <div class='panel panel-default'> $RN$");
//			         sb.append("        <div class='panel-heading col-sm-12'> $RN$");
//                     sb.append("            <h5 class='panel-title'> $RN$");
//                     sb.append("               <a data-toggle='collapse' data-parent='#accordion' href='tabs_panels.html#"+isDPLst.getAttrColumn()+"'> $RN$");   
//                     sb.append(                     isDPLst.getViewName()+"$RN$");   
//                     sb.append("               </a> $RN$");   
//                     sb.append("            </h5> $RN$");   
//                     sb.append("        </div> $RN$");   
//                     sb.append("        <div id='"+isDPLst.getAttrColumn()+"' class='panel-collapse collapse in col-sm-12'> $RN$");   
//                     sb.append("            <div class='panel-body'> $RN$");   
//                     sb.append("               <ul id='"+model.getTableName()+"Tree"+isDPLst.getAttrColumn()+"' class='ztree'  height='620px'></ul> $RN$");   
//                     sb.append("            </div>$RN$");   
//                     sb.append("        </div>$RN$");   
//                     sb.append("   </div>$RN$");    
//				}
//				 sb.append("    </div> $RN$");
//				 sb.append("  </div> $RN$");
////			 }
//		   }else if(model.getClassType().equals("2")){//如果是分类树
//			   sb.append("     <div id='tree"+model.getClassColumn()+"' > $RN$");
//			   sb.append("          <ul id='"+fenModel.getTableName()+"Tree"+model.getClassColumn()+"' class='ztree'  height='620px'></ul> $RN$");
//				sb.append("     </div> $RN$");
//		   }
//		   return sb.toString().replace("$RN$", "\r\n");
//	   }
    public static String spellUlTreeReplace(Model model, Model fenModel, String operType, List<AttrConfig> configLst) {//拼写，生成树模板的时候
        StringBuilder sb = new StringBuilder();
        List<AttrConfig> isPLst = new ArrayList<AttrConfig>();
        if (model.getClassType().equals("1")) {//如果是父子树
            if (configLst.size() > 0) {
                for (int i = 0; i < configLst.size(); i++) {
                    AttrConfig spleeCon = configLst.get(i);
                    if (1 == spleeCon.getIsParentType()) {//如果是父子树上下级关系
                        isPLst.add(spleeCon);
                    }
                }
            }
            /* 刘晶  2017-06-22 10:46 在此处添加了新方法 */
            sb.append(" <div class='panel-body col-sm-12' style='height:620px;overflow:auto;'> $RN$");
            sb.append("    <div class='panel-group'  id='accordion'> $RN$");
            for (int i = 0; i < isPLst.size(); i++) {
                AttrConfig isDPLst = isPLst.get(i);
                /* 刘晶  2017-06-22 10:46 在此处添加了新方法  */
                sb.append("    <div class='panel panel-default'> $RN$");
                sb.append("        <div class='panel-heading col-sm-12'> $RN$");
                sb.append("            <h5 class='panel-title'> $RN$");
                sb.append("               <a data-toggle='collapse' data-parent='#accordion' href='tabs_panels.html#" + isDPLst.getAttrColumn() + "'> $RN$");
                sb.append(isDPLst.getViewName() + "$RN$");
                sb.append("               </a> $RN$");
                sb.append("            </h5> $RN$");
                sb.append("        </div> $RN$");
                sb.append("        <div id='" + isDPLst.getAttrColumn() + "' class='panel-collapse collapse in col-sm-12'> $RN$");
                sb.append("            <div class='panel-body'> $RN$");
                sb.append("               <ul id='" + model.getTableName() + "Tree" + isDPLst.getAttrColumn() + "' class='ztree'></ul> $RN$");
                sb.append("            </div>$RN$");
                sb.append("        </div>$RN$");
                sb.append("   </div>$RN$");
            }
            sb.append("    </div> $RN$");
            sb.append("  </div> $RN$");
//			 }
        } else if (model.getClassType().equals("2")) {//如果是分类树
            sb.append("     <div id='tree" + model.getClassColumn() + "' > $RN$");
            sb.append("          <ul id='" + fenModel.getTableName() + "Tree" + model.getClassColumn() + "' class='ztree' style='height:620px;overflow:auto;'></ul> $RN$");
            sb.append("     </div> $RN$");
        }
        return sb.toString().replace("$RN$", "\r\n");
    }

    public static String spellUlTreeJsReplace(Model model, Model fenModel, String operType, List<AttrConfig> configLst) {//拼写，生成树模板的时候
        StringBuilder sb = new StringBuilder();
        List<AttrConfig> isPLst = new ArrayList<AttrConfig>();
        if (model.getClassType().equals("1")) {//如果是父子树
            if (configLst.size() > 0) {
                for (int i = 0; i < configLst.size(); i++) {
                    AttrConfig spleeCon = configLst.get(i);
                    if (1 == spleeCon.getIsParentType()) {//如果是父子树上下级关系
                        isPLst.add(spleeCon);
                        sb.append(" var showTree" + spleeCon.getAttrColumn() + "=document.getElementById('tree" + spleeCon.getAttrColumn() + "'); $RN$");
                    }
                }
            }
        }
        return sb.toString().replace("$RN$", "\r\n");
    }


}
